from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from app.db.noe4j_db import Neo4jClient
from app.db.session import get_db
from app.api.deps import get_current_user
from app.crud import graph as graph_crud
from app.schemas.graph import (
    Node, NodeCreate, NodeUpdate,
    Relation, RelationCreate, RelationUpdate,
    GraphResponse, SearchResult
)
from app.models.user import User
from app.models.graph import NodeType

router = APIRouter()

@router.post("/nodes", response_model=Node)
def create_node(
    node_in: NodeCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """创建节点"""
    return graph_crud.create_node(db, node_in)

@router.get("/nodes/{node_id}", response_model=Node)
def get_node(
    node_id: str,
    db: Session = Depends(get_db)
):
    """获取节点详情"""
    node = graph_crud.get_node(db, node_id)
    if not node:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="节点不存在"
        )
    return node

@router.put("/nodes/{node_id}", response_model=Node)
def update_node(
    node_id: str,
    node_in: NodeUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新节点"""
    node = graph_crud.update_node(db, node_id, node_in)
    if not node:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="节点不存在"
        )
    return node

@router.delete("/nodes/{node_id}")
def delete_node(
    node_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """删除节点"""
    success = graph_crud.delete_node(db, node_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="节点不存在"
        )
    return {"message": "节点删除成功"}

@router.post("/relations", response_model=Relation)
def create_relation(
    relation_in: RelationCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """创建关系"""
    # 验证源节点和目标节点是否存在
    source_node = graph_crud.get_node(db, relation_in.source_id)
    target_node = graph_crud.get_node(db, relation_in.target_id)
    
    if not source_node or not target_node:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="源节点或目标节点不存在"
        )
    
    return graph_crud.create_relation(db, relation_in)

@router.put("/relations/{relation_id}", response_model=Relation)
def update_relation(
    relation_id: str,
    relation_in: RelationUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新关系"""
    relation = graph_crud.update_relation(db, relation_id, relation_in)
    if not relation:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="关系不存在"
        )
    return relation

@router.delete("/relations/{relation_id}")
def delete_relation(
    relation_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """删除关系"""
    success = graph_crud.delete_relation(db, relation_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="关系不存在"
        )
    return {"message": "关系删除成功"}

@router.get("/search", response_model=SearchResult)
def search_nodes(
    keyword: str = Query(..., description="搜索关键词"),
    node_type: Optional[NodeType] = Query(None, description="节点类型"),
    skip: int = Query(0, ge=0),
    limit: int = Query(20, ge=1, le=100),
    db: Session = Depends(get_db)
):
    """搜索节点"""
    nodes, total = graph_crud.search_nodes(db, keyword, node_type, skip, limit)
    return {
        "total": total,
        "items": nodes
    }

@router.get("/nodes/{node_id}/relations", response_model=List[Relation])
def get_node_relations(
    node_id: str,
    skip: int = Query(0, ge=0),
    limit: int = Query(20, ge=1, le=100),
    db: Session = Depends(get_db)
):
    """获取节点的关系"""
    node = graph_crud.get_node(db, node_id)
    if not node:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="节点不存在"
        )
    
    relations, _ = graph_crud.get_node_relations(db, node_id, skip, limit)
    return relations

@router.get("/graph-data")
def get_graph_data(
    db: Session = Depends(Neo4jClient),
    keyword: str = Query(None, description="搜索关键词")
):
    """获取图数据，支持关键词搜索"""
    print(keyword)
    if keyword and keyword.strip():
        query = """
        MATCH (n)
        WHERE toLower(n.name) CONTAINS toLower($keyword)
        WITH n
        OPTIONAL MATCH (n)-[r]-(m)
        RETURN 
            COLLECT(DISTINCT {
                id: ID(n),
                labels: labels(n),
                properties: properties(n)
            }) + COLLECT(DISTINCT {
                id: ID(m),
                labels: labels(m),
                properties: properties(m)
            }) as nodes,
            COLLECT(DISTINCT {
                id: ID(r),
                type: type(r),
                startNode: ID(startNode(r)),
                endNode: ID(endNode(r)),
                properties: properties(r)
            }) as relationships
        """
        result = db.run_query(query, {"keyword": keyword.strip()})
        if result and len(result) > 0:
            nodes = []
            relationships = []
            
            # 处理节点
            nodes_data = result[0].get('nodes', [])
            if nodes_data:
                for node in nodes_data:
                    if node:  # 确保节点不为空
                        nodes.append({
                            "id": str(node['id']),
                            "labels": node['labels'],
                            "properties": node['properties']
                        })
            
            # 处理关系
            rels_data = result[0].get('relationships', [])
            if rels_data:
                for rel in rels_data:
                    if rel:
                        relationships.append({
                            "id": f"r{rel['id']}",
                            "type": rel['type'],
                            "startNode": str(rel['startNode']),
                            "endNode": str(rel['endNode']),
                            "properties": rel['properties']
                        })
            print("最终关系列表:", relationships)  # 打印最终的关系列表
            if nodes:
                return {
                    "nodes": nodes,
                    "relationships": relationships
                }
    
    # 如果没有关键词或没有找到匹配的节点，返回所有数据
    return {
        "nodes": db.get_all_nodes_and_relationships()[0],
        "relationships": db.get_all_nodes_and_relationships()[1]
    }